<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>

    <style>
        * {
            margin: 0;
            padding: 0;
        }

        .pp {
            position: absolute;
            left: 0;
            top: 0;
            width: 500px;
            height: 150px;
            display: flex;
            justify-content: center;
            align-items: center;
            z-index: -1;
        }
    </style>
</head>

<body>
    <canvas id="cvs" width="500" height="150"></canvas>
    <p class="pp">嗨害！！嗨害！！</p>
</body>

</html>

<script>
    //获取canvas元素
    const cvsDom = document.querySelector('#cvs')

    //生成canvas绘制元素
    const context = cvsDom.getContext('2d')

    // 绘制一个矩形填充颜色
    context.fillStyle = '#ccc';
    context.fillRect(0, 0, cvsDom.width, cvsDom.height);

    context.fillStyle = '#fff';
    context.font = '20px sans-serif';
    context.textAlign = 'center';

    context.fillText('刮开有惊喜！！！', cvsDom.width / 2, cvsDom.height / 2);
    context.fill();

    // 是否按下
    let isall = false
    // 鼠标按下事件
    cvsDom.addEventListener('mousedown', function () {
        isall = true
    }, false)

    // 鼠标移动事件
    cvsDom.addEventListener('mousemove', function (e) {
        if (isall) {
            // 获取到擦除‘橡皮’坐标
            let x = e.clientX - cvsDom.offsetLeft
            let Y = e.clientY - cvsDom.offsetTop
            context.beginPath();

            // 图像合成模式
            context.globalCompositeOperation = 'destination-out';

            // 再把橡皮坐标赋值给橡皮
            context.arc(x, Y, 10, Math.PI / 180 * 0, Math.PI / 180 * 360, false);
            context.stroke();
            context.fill();



        }
    }, false)

    // 鼠标抬起事件
    cvsDom.addEventListener('mouseup', function () {
        isall = false
    }, false)
</script>